var express = require('express');
var router = express.Router();
var Mongodb = require('../../database/mongodb');
let utils = require('./../../utils/utils');
var counters = require('../../routes/common/counter');
var CICI = require('../../routes/message/cici');

/**
 * 修复数据
 */
router.get('/fix', function(req, res, next){
  Mongodb.find("gitcommit", {"compliance" : false}, null, null, function (err, docs) {
    docs.forEach(item => {
      saveCheck(item)
      // console.log(item)
      Mongodb.update('gitcommit', { _id: item._id }, item, function (err1, data) {
        if (err1) {
          console.log(err1)
        } else {
          console.log('更新成功')
        }
      });
    })
    res.json(1)
  });
})

/**
 * 代码提交记录.
 */
router.post('/commit', function (req, res, next) {
  let data = req.body;
  if (data.object_kind === 'note') {
    saveComment(data, res)
  } else if (data.object_kind === 'push') {
    saveCommit(data, res)
  } else {
    console.log(data.object_kind)
    res.json('解析失败')
  }
});

function saveCommit(commitData, res) {
  let saveDocs = []
  commitData.commits.forEach(commit => {
    let obj = initCommitObj(commitData, commit);
    console.log(obj)
    if (saveCheck(obj)) {
      saveDocs.push(obj)
    }
  })
  if (saveDocs.length > 0) {
    console.log('保存提交记录：')
    Mongodb.saveDocs("gitcommit", saveDocs, function (err, docs) {
      if (err) {
        res.send("保存失败");
      } else {
        res.json(docs);
      }
    });
    // res.json(saveDocs)
  }
}

/**
 * 初始化提交信息.
 * @param {*} commitData 
 * @param {*} commit 
 */
function initCommitObj (commitData, commit) {
  let obj = utils.deepCopy(commitData);
  obj.user_email = commit.author.email
  obj.createDate = new Date()
  obj.repositoryname = commitData.repository.name
  obj.repositorydescription = commitData.repository.description
  obj.commitid = commit.id
  obj.commitmessage = commit.message
  obj.commitDate = new Date(commit.timestamp)
  obj.commitUrl = initcommitUrl(commit.url)
  obj.state = 'TODO'
  obj.businessIds = []
  obj.checkInfos = []
  return obj
}

function initcommitUrl (url) {
  let result = url
  if (url) {
    result = url.replace('c6edc0a07830', '10.50.0.76:8080')
  }
  return result
}

/**
 * 提交检测-1.0.
 * 参考业界规范，同时考虑九天单号.
 * @param {commit} commit 
 */
function saveCheck1 (commit) {
  let result = true
  const commitPattern = /^(feat|fix|refactor|docs|style|review|test)\(((R[0-9]{8}(\s|#)(S|T)[0-9]{8})|(B[0-9]{8}))\)(:|：|).+$/
  const typePattern = /^(feat|fix|refactor|docs|style|review|test)/
  const rPattern = /[RB]{1}[0-9]{8}/g
  const sPattern = /[ST]{1}[0-9]{8}/g
  const specialPattern = /(jenbkins|Merge)/

  // jenkins构建、代码合并提交不记录
  commit.commitmessage = commit.commitmessage.replace(/\n/g, '')
  console.log(commit.commitmessage)
  if (!specialPattern.test(commit.commitmessage)) {
    // 格式校验
    if (commitPattern.test(commit.commitmessage)) {
      console.log('格式校验通过')
      commit.compliance = true
      // 获取类型
      commit.commitType = commit.commitmessage.match(typePattern)[0].toUpperCase()

      // 获取单号
      let rid = commit.commitmessage.match(rPattern)[0].toUpperCase()
      let sid
      if (sPattern.test(commit.commitmessage)) {
        sid = commit.commitmessage.match(sPattern)[0].toUpperCase()
      }
      console.log('单号：' + rid + ',' + sid)
      if (/00000000/.test(rid) || /00000000/.test(sid)) {
        commit.compliance = false
        commit.checkInfos.push('单号校验不通过')
        CICI.remindMess(commit.user_email,
          '【代码提交格式不规范】请确认单号是否正确\n实际：' + commit.commitmessage,
          'https://test/works/#/code/commits',
          () => {}
        )
      }
      commit.businessIds.push(rid)
      if (sid) {
        commit.businessIds.push(sid)
      }
    } else {
      console.log('格式校验不通过')
      commit.compliance = false
      commit.checkInfos.push('代码提交格式校验不通过')
      CICI.remindMess(commit.user_email,
        '【代码提交格式不规范】\n实际：' + commit.commitmessage + '\n标准：<类型>(<单号>): <描述>\n类型：feat/fix/style/refactor/docs\n单号：九天产品需求单 故事/任务单或缺陷单',
        'https://test/works/#/code/commits',
        () => {}
      )
    }
  } else {
    result = false
  }
  return result
}

/**
 * 提交检测-2.0.
 * 按公司规范调整.
 * @param {commit} commit 
 */
function saveCheck (commit) {
  let result = true

  const commitPattern = /^[RSTB]\d{8}\s.+$/
  const rPattern = /[RSTB]\d{8}/g
  const specialPattern = /(jenbkins|Merge)/
  const emailPattern = /^.+@sachuangwei\.com$/

  // 邮箱检查
  // if (!emailPattern.test(commit.user_email)) {
  //   CICI.remindMess("panduo@sachuangwei.com",
  //     '【git邮箱配置不正确】用户' + commit.user_name + '邮箱配置不正确，实际为：' + commit.user_email,
  //     'https://test/works/#/code/commits',
  //     () => {}
  //   )
  // }

  commit.commitmessage = commit.commitmessage.replace(/\n/g, '')
  // jenkins构建、代码合并提交不记录
  if (!specialPattern.test(commit.commitmessage)) {
    // 格式校验
    if (commitPattern.test(commit.commitmessage)) {
      commit.compliance = true
    } else {
      commit.compliance = false
      commit.checkInfos.push('代码提交格式校验不通过')
      // CICI.remindMess(commit.user_email,
      //   '【代码提交格式不规范】\n实际：' + commit.commitmessage + '\n标准：单号 <描述>\n单号：九天产品需求单 故事/任务单或缺陷单',
      //   'https://test/works/#/code/commits',
      //   () => {}
      // )
    }
    // 获取单号
    let rid = commit.commitmessage.match(rPattern)[0].toUpperCase()
    if (/00000000/.test(rid)) {
      commit.compliance = false
      commit.checkInfos.push('单号校验不通过')
      // CICI.remindMess(commit.user_email,
      //   '【代码提交格式不规范】请安规范提交单号\n实际：' + commit.commitmessage,
      //   'https://test/works/#/code/commits',
      //   () => {}
      // )
    }
    commit.businessIds.push(rid)
  } else {
    result = false
  }
  return result
}

function saveComment(data, res) {
  counters.getNextSequenceValue('COMMENT_ID', (value) => {
    data.id = value
    data.state = 'TODO'
    data.createDate = new Date()
    Mongodb.save("gitcomment", data, function (err, docs) {
      if (err) {
        res.send("保存失败");
      } else {
        res.json(docs);
      }
    });
  })
}

module.exports = router;